#include "..\..\Header\Platform\fwWindowsOpenGLES.h"
#include "..\..\Header\Config\fwMacro.h"
#include "..\..\Header\Config\fwConfig.h"
#include "..\..\Header\fwLog.h"
#include "..\..\Header\Game\fwGlobal.h"

WindowsOpenGLESv2::WindowsOpenGLESv2(char * szTitle, int iFlags)
:Windows()
{
	m_szTitle = szTitle;
	m_iFlags = iFlags;
}

WindowsOpenGLESv2::~WindowsOpenGLESv2()
{

}

int WindowsOpenGLESv2::Init()
{
	LOGI("Init Windows for run openglesv2.\n");
	return !CreateWindows(); //if CreateWindows return true, it will return 0
}

void WindowsOpenGLESv2::Destroy()
{
	SAFE_DEL_ARRAY(m_szTitle);
}


bool WindowsOpenGLESv2::CreateWindows()
{
	EGLint attribList[] =
	{
		EGL_RED_SIZE, 5,
		EGL_GREEN_SIZE, 6,
		EGL_BLUE_SIZE, 5,
		EGL_ALPHA_SIZE, (m_iFlags & ES_WINDOW_ALPHA) ? 8 : EGL_DONT_CARE,
		EGL_DEPTH_SIZE, (m_iFlags & ES_WINDOW_DEPTH) ? 8 : EGL_DONT_CARE,
		EGL_STENCIL_SIZE, (m_iFlags & ES_WINDOW_STENCIL) ? 8 : EGL_DONT_CARE,
		EGL_SAMPLE_BUFFERS, (m_iFlags & ES_WINDOW_MULTISAMPLE) ? 1 : 0,
		EGL_NONE
	};

	if (!CreateClientWindows())
	{
		return GL_FALSE;
	}
#if CURRENT_PLATFORM == PLATFORM_WIN32 && CURRENT_LIB == GRAPHICS_LIB_OPENGLES_20
	if (!m_pESContext->CreateESContext(attribList))
	{
		return GL_FALSE;
	}
#else
	return GL_FALSE;
#endif

	return EGL_TRUE;
}

bool WindowsOpenGLESv2::CreateClientWindows()
{
	WNDCLASS wndclass = { 0 };
	DWORD    wStyle = 0;
	RECT     windowRect;
	HINSTANCE hInstance = GetModuleHandle(NULL);


	wndclass.style = CS_OWNDC;
	wndclass.lpfnWndProc = (WNDPROC)WinProc;
	wndclass.hInstance = hInstance;
	wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wndclass.lpszClassName = TEXT("opengles2.0");

	if (!RegisterClass(&wndclass))
		return FALSE;

	wStyle = WS_VISIBLE | WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION;

	// Adjust the window rectangle so that the client area has
	// the correct number of pixels
	windowRect.left = 0;
	windowRect.top = 0;
	windowRect.right = GameGlobal::iWidth;
	windowRect.bottom = GameGlobal::iHeight;

	AdjustWindowRect(&windowRect, wStyle, FALSE);

#if CURRENT_PLATFORM == PLATFORM_WIN32 && CURRENT_LIB == GRAPHICS_LIB_OPENGLES_20
	m_pESContext->_eglHWND = CreateWindow(
		"opengles2.0",
		m_szTitle,
		wStyle,
		0,
		0,
		windowRect.right - windowRect.left,
		windowRect.bottom - windowRect.top,
		NULL,
		NULL,
		hInstance,
		NULL);

	if (m_pESContext->_eglHWND == NULL)
		return GL_FALSE;

	ShowWindow(m_pESContext->_eglHWND, TRUE);
#else
	return GL_FALSE;
#endif

	return GL_TRUE;
}

void WindowsOpenGLESv2::KeyboardUpdate(WPARAM wParam, bool status)
{

}

void WindowsOpenGLESv2::MouseUpdate()
{

}